let deckId = null;
let deckName = "新卡组";

// 页面加载时获取URL参数
window.onload = function () {
    const urlParams = new URLSearchParams(window.location.search);
    deckId = urlParams.get('id');
    if (!deckId) {
        deckId = -1;
    }
    initDeckInfo(deckId);
    // 获取候选角色
    fetchCandidateRoles();
    // 获取候选卡牌
    fetchCandidateCards();
};

// 初始化卡组信息
function initDeckInfo(id) {
    fetch(`/api/deck/init/${id}`)
        .then(response => response.json())
        .then(data => {
            deckName = data.name;
            document.getElementById('deckName').textContent = deckName;
            // 填充卡组内容
            populateDeck(data);
        })
        .catch(error => console.error('获取卡组信息失败:', error));
}

// 获取卡组信息
function fetchDeck(id) {
    fetch(`/api/deck/${id}`)
        .then(response => response.json())
        .then(data => {
            deckName = data.name;
            document.getElementById('deckName').textContent = deckName;
            // 填充卡组内容
            populateDeck(data);
        })
        .catch(error => console.error('获取卡组信息失败:', error));
}

// 获取候选角色
function fetchCandidateRoles() {
    if (!deckId)
        fetch(`/api/deck/candidate-roles/-1`)
            .then(response => response.json())
            .then(data => {
                // 填充候选角色
                populateCandidateRoles(data);
            })
            .catch(error => console.error('获取候选角色失败:', error));
    else
        fetch(`/api/deck/candidate-roles/${deckId}`)
            .then(response => response.json())
            .then(data => {
                // 填充候选角色
                populateCandidateRoles(data);
            })
            .catch(error => console.error('获取候选角色失败:', error));
}

// 获取候选卡牌
function fetchCandidateCards() {
    if (!deckId)
        fetch(`/api/deck/candidate-cards/-1`)
            .then(response => response.json())
            .then(data => {
                // 填充候选卡牌
                populateCandidateCards(data);
            })
            .catch(error => console.error('获取候选卡牌失败:', error));
    else
        fetch(`/api/deck/candidate-cards/${deckId}`)
            .then(response => response.json())
            .then(data => {
                // 填充候选卡牌
                populateCandidateCards(data);
            })
}

// 填充卡组内容
function populateDeck(data) {
    // 根据卡牌类型分配到不同区域
    data.cards.forEach(card => {
        // console.log(card);
        const cardElement = createCardElement(card);
        cardElement.addEventListener('click', () => {
            removeCardFromDeck(card.id);
        });
        switch (card.type) {
            case 'role':
                document.getElementById('fieldRoleList').appendChild(cardElement);
                break;
            case 'action':
                document.getElementById('actionList').appendChild(cardElement);
                break;
            case 'total_weapon':
                document.getElementById('fieldWeaponList').appendChild(cardElement);
                break;
            case 'role_weapon':
                document.getElementById('roleWeaponList').appendChild(cardElement);
                break;
        }
    });
    // 分配角色
    if (data.leaderRole) {
        const roleElement = createRoleElement(data.leaderRole);
        roleElement.addEventListener('click', () => {
            removeRoleFromDeck();
        });
        document.getElementById('roleList').appendChild(roleElement);
    }
}

// 填充候选角色
function populateCandidateRoles(roles) {
    const container = document.getElementById('candidateRoles');
    roles.forEach(role => {
        const roleElement = createRoleElement(role);
        roleElement.addEventListener('click', () => {
            addRoleToDeck(role.id);
        });
        container.appendChild(roleElement);
    });
}

// 填充候选卡牌
function populateCandidateCards(cards) {
    const container = document.getElementById('candidateCards');
    cards.forEach(card => {
        const cardElement = createCardElement(card);
        cardElement.addEventListener('click', () => {
            addCardToDeck(card.id);
        });
        container.appendChild(cardElement);
    });
}

// 添加角色到卡组
function addRoleToDeck(roleId) {
    console.log(deckId, roleId);
    if (!deckId) {
        console.log('addRoleToDeck no deckId');
        alert('请先创建卡组');
        return;
    }
    let response = fetch(`/api/deck/add-role/${deckId}/${roleId}`);

    response.then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清空卡组
                document.getElementById('roleList').innerHTML = '';
                document.getElementById('fieldRoleList').innerHTML = '';
                document.getElementById('actionList').innerHTML = '';
                document.getElementById('fieldWeaponList').innerHTML = '';
                document.getElementById('roleWeaponList').innerHTML = '';
                // 清空候选角色
                document.getElementById('candidateRoles').innerHTML = '';
                // 更新卡组
                fetchDeck(deckId);
                // 更新候选角色
                fetchCandidateRoles();
            }
            else {
                alert('添加失败：' + data.message + (data.body ? '：' + data.body : ''));
            }
        });
}

// 移除角色到卡组
function removeRoleFromDeck() {
    if (!deckId) {
        console.log('removeRoleFromDeck no deckId');
        alert('请先创建卡组');
        return;
    }
    let response = fetch(`/api/deck/remove-role/${deckId}`);

    response.then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清空卡组
                document.getElementById('roleList').innerHTML = '';
                document.getElementById('fieldRoleList').innerHTML = '';
                document.getElementById('actionList').innerHTML = '';
                document.getElementById('fieldWeaponList').innerHTML = '';
                document.getElementById('roleWeaponList').innerHTML = '';
                // 清空候选角色
                document.getElementById('candidateRoles').innerHTML = '';
                // 更新卡组
                fetchDeck(deckId);
                // 更新候选角色
                fetchCandidateRoles();
            }
            else {
                alert('移除失败：' + data.message);
            }
        });
}

// 添加卡牌到卡组
function addCardToDeck(cardId) {
    if (!deckId) {
        console.log('addCardToDeck no deckId');
        alert('请先创建卡组');
        return;
    }
    let response = fetch(`/api/deck/add-card/${deckId}/${cardId}`);

    response.then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清空卡组
                document.getElementById('roleList').innerHTML = '';
                document.getElementById('fieldRoleList').innerHTML = '';
                document.getElementById('actionList').innerHTML = '';
                document.getElementById('fieldWeaponList').innerHTML = '';
                document.getElementById('roleWeaponList').innerHTML = '';
                // 清空候选卡牌
                document.getElementById('candidateCards').innerHTML = '';
                // 更新卡组
                fetchDeck(deckId);
                // 更新候选卡牌
                fetchCandidateCards();
            } else {
                alert('添加失败：' + data.message);
            }
        });
}

// 移除卡牌
function removeCardFromDeck(cardId) {
    if (!deckId) {
        console.log('removeCardFromDeck no deckId');
        alert('请先创建卡组');
        return;
    }
    let response = fetch(`/api/deck/remove-card/${deckId}/${cardId}`);

    response.then(response => response.json())
        .then(data => {
            if (data.success) {
                // 清空卡组
                document.getElementById('roleList').innerHTML = '';
                document.getElementById('fieldRoleList').innerHTML = '';
                document.getElementById('actionList').innerHTML = '';
                document.getElementById('fieldWeaponList').innerHTML = '';
                document.getElementById('roleWeaponList').innerHTML = '';
                // 清空候选卡牌
                document.getElementById('candidateCards').innerHTML = '';
                // 更新卡组
                fetchDeck(deckId);
                // 更新候选卡牌
                fetchCandidateCards();
            } else {
                alert('移除失败：' + data.message);
            }
        });
}

// 修改卡组名称
function editDeckName() {
    const newName = prompt('请输入新的卡组名称:', deckName);
    if (newName && newName.trim()) {
        deckName = newName.trim();
        document.getElementById('deckName').textContent = deckName;
    }
}

// 保存卡组
function saveDeck() {
    const deckData = {
        id: deckId,
        name: deckName,
        role: getLeaderRoleId(),
        cards: collectDeckCards()
    };

    fetch('/api/deck/save')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('保存成功！');
            } else {
                alert('保存失败：' + data.message);
            }
        });
}

// 删除卡组
function deleteDeck() {
    if (!deckId) {
        window.location.href = '/deck-bag.html';
        return;
    }
    let response = fetch(`/api/deck/${deckId}`, {
        method: 'DELETE'
    });

    response.then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('删除成功！');
                window.location.href = '/deck-bag.html';
            } else {
                alert('删除失败：' + data.message);
            }
        });
}

// 获取主将角色ID
function getLeaderRoleId() {
    const leaderRole = document.querySelector('#roleList .card');
    return leaderRole ? parseInt(leaderRole.id.split('-')[1]) : null;
}

// 收集卡组中的所有卡牌
function collectDeckCards() {
    const cardCounts = new Map();
    const sections = ['fieldRoleList', 'actionList', 'fieldWeaponList', 'roleWeaponList'];

    sections.forEach(sectionId => {
        const section = document.getElementById(sectionId);
        section.querySelectorAll('.card').forEach(cardElement => {
            const cardId = parseInt(cardElement.id.split('-')[1]);
            cardCounts.set(cardId, (cardCounts.get(cardId) || 0) + 1);
        });
    });

    return Object.fromEntries(cardCounts);
}